package com.bishe.demo.config.shiro;


import com.bishe.demo.modules.account.entity.Resource;
import com.bishe.demo.modules.account.entity.Role;
import com.bishe.demo.modules.account.entity.User;
import com.bishe.demo.modules.account.service.ResourceService;
import com.bishe.demo.modules.account.service.RoleService;
import com.bishe.demo.modules.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        Role role = roleService.getRoleByUserId(user.getUserId());
        simpleAuthorizationInfo.addRole(role.getRoleName());
        List<Resource> resources = resourceService.getResourcesByRoleId(role.getRoleId());
        resources.stream().forEach(resource -> {
            simpleAuthorizationInfo.addStringPermission(resource.getPermission());
        });
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user = userService.getUserByUserName(userName);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
